{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "path=\"./images/shapes.png\"\n",
    "img=cv2.imread(path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def stackImages(scale,imgArray):\n",
    "    rows = len(imgArray)\n",
    "    cols = len(imgArray[0])\n",
    "    rowsAvailable = isinstance(imgArray[0], list)\n",
    "    width = imgArray[0][0].shape[1]\n",
    "    height = imgArray[0][0].shape[0]\n",
    "    if rowsAvailable:\n",
    "        for x in range ( 0, rows):\n",
    "            for y in range(0, cols):\n",
    "                if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:\n",
    "                    imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)\n",
    "                else:\n",
    "                    imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)\n",
    "                if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)\n",
    "        imageBlank = np.zeros((height, width, 3), np.uint8)\n",
    "        hor = [imageBlank]*rows\n",
    "        hor_con = [imageBlank]*rows\n",
    "        for x in range(0, rows):\n",
    "            hor[x] = np.hstack(imgArray[x])\n",
    "        ver = np.vstack(hor)\n",
    "    else:\n",
    "        for x in range(0, rows):\n",
    "            if imgArray[x].shape[:2] == imgArray[0].shape[:2]:\n",
    "                imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)\n",
    "            else:\n",
    "                imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)\n",
    "            if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)\n",
    "        hor= np.hstack(imgArray)\n",
    "        ver = hor\n",
    "    return ver"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def getContours(img):\n",
    "    \n",
    "    # RETR_EXTERNAL:检索极端外部轮廓\n",
    "    contours,hierarchy = cv2.findContours(img,mode=cv2.RETR_EXTERNAL,\n",
    "                                          method=cv2.CHAIN_APPROX_NONE)\n",
    "    \n",
    "    for cnt in contours:\n",
    "        area=cv2.contourArea(cnt)\n",
    "        \n",
    "        if area>500:\n",
    "            # 画出轮廓\n",
    "            # (载体,轮廓,-1,颜色,厚度)\n",
    "            cv2.drawContours(imgContour,cnt,-1,(255,0,0),3)\n",
    "            # 计算轮廓的长度\n",
    "            peri=cv2.arcLength(cnt,True)\n",
    "            \n",
    "            # 计算近似拐角点\n",
    "            approx=cv2.approxPolyDP(cnt,0.02*peri,True)\n",
    "            \n",
    "            objCor=len(approx)\n",
    "            \n",
    "            # 创建边界框\n",
    "            x,y,w,h=cv2.boundingRect(approx)\n",
    "            \n",
    "            if objCor == 3:\n",
    "                objectType=\"Tri\"\n",
    "            elif objCor == 4:\n",
    "                aspRatio=w/float(h)\n",
    "                if aspRatio > 0.95 and aspRatio < 1.05 :\n",
    "                    objectType = \"Square\"\n",
    "                else:\n",
    "                    objectType = \"Rectangle\"\n",
    "            else:\n",
    "                objectType = \"Cicle\"\n",
    "            cv2.rectangle(imgContour,(x,y),(x+w,y+h),(0,255,0),2)\n",
    "            \n",
    "            # 标注\n",
    "            # (载体,类型,位置,字体,比例,颜色,厚度)\n",
    "            cv2.putText(imgContour,objectType,\n",
    "                        (x+(w//2)-10,y+(h//2)-10),cv2.FONT_HERSHEY_COMPLEX,\n",
    "                        0.5,(0,0,0),2)\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "113"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "imgContour=img.copy()\n",
    "imgGray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "imgBlur=cv2.GaussianBlur(imgGray,(7,7),1)\n",
    "imgCanny=cv2.Canny(imgBlur,50,50)\n",
    "imgBlank=np.zeros_like(img)\n",
    "\n",
    "getContours(imgCanny)\n",
    "\n",
    "imgStack=stackImages(0.65,([img,imgGray,imgBlur],\n",
    "                          [imgCanny,imgContour,imgBlank]))\n",
    "\n",
    "cv2.imshow(\"Stack\",imgStack)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
